package com.edu.app.controller.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.app.bean.core.*;
import com.edu.app.bean.core.popup.CustomersPop;
import com.edu.app.bean.linkbeans.SysCustomerActivity;
import com.edu.app.bean.linkbeans.SysUserCustomer;
import com.edu.app.bean.virtualbean.SelectedItems;
import com.edu.app.constant.ErrorConstant;
import com.edu.app.constant.StaticConstant;
import com.edu.app.constant.SysMessage;
import com.edu.app.service.sys.app.teacher.SysCutomerActFeedbackService;
import com.edu.app.service.sys.core.SysContractService;
import com.edu.app.service.sys.core.SysCustomerService;
import com.edu.app.service.sys.core.SysListOfValueService;
import com.edu.app.service.sys.customize.SysCustomerExtensionYlynService;
import com.edu.app.service.sys.linkservices.*;
import com.edu.app.threadlocal.TenantContext;
import com.edu.app.util.CommonUtils;
import com.edu.app.util.ErrorUtil;
import com.edu.app.util.JWTUtil;
import com.edu.app.util.MsgUtil;

import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/api/customers")
@RestController
public class SysCustomerController {

    @Autowired
    private SysCustomerService sysCustomerService;

    @Autowired
    private SysUserCustomerService sysUserCustomerService;

    @Autowired
    private SysCustomerActivityService sysCustomerActivityService;

    @Autowired
    private SysCutomerActFeedbackService sysCutomerActFeedbackService;

    @Autowired
    private SysCustomerLessonService sysCustomerLessonService;

    @Autowired
    private SysContractService sysContractService;

    @Autowired
    private SysContractLessonService sysContractLessonService;

    @Autowired
    private SysUserContractService sysUserContractService;

    @Autowired
    private SysCustomerExtensionYlynService sysCustomerExtensionYlynService;

    @Autowired
    private SysListOfValueService sysListOfValueService;

    @Autowired
    private SysUserActivityService sysUserActivityService;

    @PostMapping(value = "importCustomers")
    @RequiresAuthentication
    public ModelMap importCustomers(@RequestHeader("Authorization") String token, @RequestBody String customerListStr, @RequestParam String quality_tag, @RequestParam String channel_tag){
        try{
            String username = JWTUtil.getUsername(token);
            //List<SysCustomer> sysCustomerList = JSON.parseArray(data, SysCustomer.class);
            JSONObject obj = (JSONObject) JSON.parse(customerListStr);
            List<SysCustomer> sysCustomerList = JSON.parseArray(obj.get("customerListStr").toString(), SysCustomer.class);
            String str = "";
            for(SysCustomer tmp: sysCustomerList){
                tmp.initializeSystemColumns(username);
                tmp.setQuality_tag(quality_tag);
                tmp.setChannel_tag(channel_tag);
                tmp.setStatus(8);//set status 8 means, this is the raw list
                if(tmp.getBirthday() != null){
                    str += "(\"" + tmp.getCreate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getUpdate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getName() + "\",\"" + tmp.getPhone() + "\"," + tmp.getSex() + "," + "\"" + CommonUtils.dateToString(tmp.getBirthday()) + "\"" + "," + tmp.getStatus() + ",\"" +tmp.getQuality_tag() + "\",\"" + tmp.getChannel_tag() + "\")";
                }else{
                    str += "(\"" + tmp.getCreate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getUpdate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getName() + "\",\"" + tmp.getPhone() + "\"," + tmp.getSex() + ","  + tmp.getBirthday()  + "," + tmp.getStatus() + ",\"" +tmp.getQuality_tag() + "\",\"" + tmp.getChannel_tag() + "\")";
                }

                str += ",";
            }
            str = str.substring(0, str.length() - 1);

            sysCustomerService.importCustomers(str);
            return MsgUtil.retMsg(SysMessage.ADD_CUSTOMER_SUCCEED, null,null);

        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @PostMapping(value = "importMembers")
    @RequiresAuthentication
    public ModelMap importMembers(@RequestHeader("Authorization") String token, @RequestBody String customerListStr){
        try{
            String username = JWTUtil.getUsername(token);
            JSONObject obj = (JSONObject) JSON.parse(customerListStr);
            List<SysCustomer> sysCustomerList = JSON.parseArray(obj.get("customerListStr").toString(), SysCustomer.class);
            String str = "";
            for(SysCustomer tmp: sysCustomerList){
                tmp.initializeSystemColumns(username);
                tmp.setStatus(1);//set status 1 means, this is the member list
                if(tmp.getBirthday() != null){
                    str += "(\"" + tmp.getCreate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getUpdate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getName() + "\",\"" + tmp.getPhone() + "\"," + tmp.getSex() + "," + "\"" + CommonUtils.dateToString(tmp.getBirthday()) + "\"" + "," + tmp.getStatus() + ",\"" +tmp.getQuality_tag() + "\",\"" + tmp.getChannel_tag() + "\")";
                }else{
                    str += "(\"" + tmp.getCreate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getUpdate_by() + "\",\"" + CommonUtils.dateToString(tmp.getCreate_time()) + "\",\"" + tmp.getName() + "\",\"" + tmp.getPhone() + "\"," + tmp.getSex() + ","  + tmp.getBirthday()  + "," + tmp.getStatus() + ",\"" +tmp.getQuality_tag() + "\",\"" + tmp.getChannel_tag() + "\")";
                }

                str += ",";
            }
            str = str.substring(0, str.length() - 1);

            sysCustomerService.importCustomers(str);
            return MsgUtil.retMsg(SysMessage.ADD_CUSTOMER_SUCCEED, null,null);

        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping(value = "")
    @RequiresAuthentication
    public ModelMap getCustomerList (){
        try{
            List<SysCustomer> customerList = sysCustomerService.getObjectList();
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_SUCCEED, StaticConstant.CUSTOMER_LIST, customerList);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping(value = "/getCustomerNoByChannelTag")
    @RequiresAuthentication
    public ModelMap getCustomerNoByChannelTag (@RequestParam("channel_tag") String channel_tag){
        try{
            Integer number = sysCustomerService.getCustomerNoByChannelTag(channel_tag);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_NUMBER_SUCCEED, "number", number);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping(value = "/customers_pop")
    @RequiresAuthentication
    //@RequiresRoles(value = {StaticConstant.ADMIN_ROLE})
    public ModelMap getUsersPop (){
        try{
            List<CustomersPop> customersPop = sysCustomerService.getCustomersPop();
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_SUCCEED, "pop_list", customersPop);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping(value = "/not_assigned_customers")
    @RequiresAuthentication
    //@RequiresRoles(value = {StaticConstant.ADMIN_ROLE})
    public ModelMap not_assigned_customers (){
        try{
            List<CustomersPop> customersPop = sysCustomerService.getNotAssignedCustomersPop();
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_SUCCEED, "pop_list", customersPop);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages")
    @RequiresAuthentication
    public ModelMap getCustomerByPage(@RequestHeader("Authorization") String token,
                                      @RequestParam Integer offset,
                                      @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCustomerService.findItemByPage(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages/getCustomer")
    @RequiresAuthentication
    public ModelMap getCustomer(@RequestHeader("Authorization") String token,
                                      @RequestParam Integer offset,
                                      @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCustomerService.getCustomer(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages/getPoCustomer")
    @RequiresAuthentication
    public ModelMap getPoCustomer(@RequestHeader("Authorization") String token,
                                  @RequestParam Integer offset,
                                  @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCustomerService.getPoCustomer(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages/getPoCustomerToday")
    @RequiresAuthentication
    public ModelMap getPoCustomerToday(@RequestHeader("Authorization") String token,
                                       @RequestParam Integer offset,
                                       @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCustomerService.getPoCustomerToday(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages/getPoCustomerAssigned")
    @RequiresAuthentication
    public ModelMap getPoCustomerAssigned(@RequestHeader("Authorization") String token,
                                       @RequestParam Integer offset,
                                       @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCustomerService.getPoCustomerAssigned(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages/getPoCustomerNotAssigned")
    @RequiresAuthentication
    public ModelMap getPoCustomerNotAssigned(@RequestHeader("Authorization") String token,
                                       @RequestParam Integer offset,
                                       @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCustomerService.getPoCustomerNotAssigned(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    //getCustomerById
    @GetMapping(value = "/{id}")
    @RequiresAuthentication
    public ModelMap getCustomerById(@PathVariable Integer id){
        try{
            SysCustomer sysCustomer = sysCustomerService.getObjectById(id);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_SUCCEED, StaticConstant.CUSTOMER, sysCustomer);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    //getCustomerById
    @GetMapping(value = "/searchCustomer")
    @RequiresAuthentication
    public ModelMap getCustomer(@RequestParam("name") String name){
        try{
            List<SysCustomer> sysCustomerList = sysCustomerService.searchCustomer(name.replace(" ",""));
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_SUCCEED, StaticConstant.CUSTOMER_LIST, sysCustomerList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @PostMapping(value = "/addCustomerFromOutside")
    public ModelMap addNewCustomer(@RequestBody SysCustomer sysCustomer, @RequestParam String referrer_channel, @RequestParam Integer customer_activity_id, @RequestParam Integer feedback_id, @RequestParam Integer tenant_id){
        try{
            TenantContext.setNeedTenantId(Boolean.FALSE);
            sysCustomer.initializeSystemColumns("admin");
            Integer id = 0;
            List<SysListOfValue> sysListOfValueList = sysListOfValueService.getObjectListByType("S_LOV_REFER_CHANNEL_FEEDBACK");
            for(SysListOfValue listOfValue: sysListOfValueList){
                id = listOfValue.getId();
            }
            if(id != 0){
                sysCustomer.setRefer_channel_id(id);
            }

            SysCustomerActivity sysCustomerActivity = sysCustomerActivityService.getObjectById(customer_activity_id);
            sysCustomer.setRefer_customer_id(sysCustomerActivity.getCustomer_id());
            List<SysUser> sysUserList = sysUserActivityService.getUserByActivityId(sysCustomerActivity.getActivity_id());

            for(SysUser sysUser: sysUserList){
                sysCustomer.setRefer_user_id(sysUser.getId());
            }

            sysCustomer.setRefer_feedback_id(feedback_id);
            sysCustomer.setTenant_id(tenant_id);

            sysCustomerService.add(sysCustomer);

            TenantContext.setNeedTenantId(Boolean.TRUE);
            return MsgUtil.retMsg(SysMessage.ADD_CUSTOMER_SUCCEED, null,null);

        }catch (org.springframework.dao.DuplicateKeyException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new DuplicateKeyException("该客户已存在");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @PostMapping(value = "")
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public ModelMap addCustomer(@RequestHeader("Authorization") String token,
                                @RequestBody SysCustomer sysCustomer,
                                @RequestParam String salesList,
                                @RequestParam String teachersList){

        try{
            String username = JWTUtil.getUsername(token);
            sysCustomer.initializeSystemColumns(username);
            Integer r = sysCustomerService.add(sysCustomer);
            if(r > 0){
                List<SelectedItems> selectedItems = JSON.parseArray(salesList, SelectedItems.class);
                //Assign customer to corresponding users
                for(int i=0; i<selectedItems.size(); i++){
                    SysUserCustomer tmp = new SysUserCustomer(selectedItems.get(i).getValue(), sysCustomer.getId());
                    tmp.initializeSystemColumns(username);
                    tmp.setRoleplay("consultant");
                    sysUserCustomerService.add(tmp);
                }

                selectedItems = JSON.parseArray(teachersList, SelectedItems.class);
                for(int i=0; i<selectedItems.size(); i++){
                    SysUserCustomer tmp = new SysUserCustomer(selectedItems.get(i).getValue(), sysCustomer.getId());
                    tmp.initializeSystemColumns(username);
                    tmp.setRoleplay("teacher");
                    sysUserCustomerService.add(tmp);
                }

                return MsgUtil.retMsg(SysMessage.ADD_CUSTOMER_SUCCEED, "customer_id",sysCustomer.getId());
            }else{
                return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
            }
        }catch (org.springframework.dao.DuplicateKeyException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new DuplicateKeyException("该客户手机号已存在");
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //return ErrorUtil.retErrMsg(ErrorConstant.CUSTOMER_PHONE_ALREADY_EXISTS);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @PutMapping(value = {""})
    @RequiresAuthentication
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public ModelMap update (@RequestHeader("Authorization") String token,
                            @RequestBody SysCustomer sysCustomer,
                            @RequestParam String salesList,
                            @RequestParam String teachersList){

        try{
            String username = JWTUtil.getUsername(token);
            sysCustomer.initializeUpdateSystemColumns(username);
            SysCustomer oldCus = sysCustomerService.getObjectById(sysCustomer.getId());
            sysCustomer.setCreate_by(oldCus.getCreate_by());
            sysCustomer.setCreate_time(oldCus.getCreate_time());
            sysCustomerService.update(sysCustomer);

            //before update, to delete the existed relationship
            sysUserCustomerService.deleteUserCustomerByCustomerId(sysCustomer.getId());

            List<SelectedItems> selectedItems = JSON.parseArray(salesList, SelectedItems.class);
            //Assign customer to corresponding users
            for(int i=0; i<selectedItems.size(); i++){
                SysUserCustomer tmp = new SysUserCustomer(selectedItems.get(i).getValue(), sysCustomer.getId());
                tmp.initializeSystemColumns(username);
                tmp.setRoleplay("consultant");
                sysUserCustomerService.add(tmp);
            }

            selectedItems = JSON.parseArray(teachersList, SelectedItems.class);
            for(int i=0; i<selectedItems.size(); i++){
                SysUserCustomer tmp = new SysUserCustomer(selectedItems.get(i).getValue(), sysCustomer.getId());
                tmp.initializeSystemColumns(username);
                tmp.setRoleplay("teacher");
                sysUserCustomerService.add(tmp);
            }
            return MsgUtil.retMsg(SysMessage.UPDATE_CUSTOMER_SUCCEED, null,null);
        }catch (org.springframework.dao.DuplicateKeyException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new DuplicateKeyException("该客户手机号已存在");
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //return ErrorUtil.retErrMsg(ErrorConstant.CUSTOMER_PHONE_ALREADY_EXISTS);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @DeleteMapping(value = "")
    @RequiresRoles(value = {StaticConstant.ADMIN_ROLE})
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public ModelMap delete (@RequestParam Integer id){
        try{
            //before deleting customer, make sure all the related parents items are cleaned up.
            //Deleting customer is so expensive, don't do this often
            sysUserCustomerService.deleteUserCustomerByCustomerId(id);

            List<SysActivity> sysActivityList = sysCustomerActivityService.getActivityByCustomerId(id);
            for(SysActivity sysActivity: sysActivityList){
                SysCustomerActivity sysCustomerActivity = sysCustomerActivityService.getCustomerActivity(id, sysActivity.getId());
                sysCutomerActFeedbackService.deleteCustomerActFeedbackByActId(sysCustomerActivity.getId());
            }

            sysCustomerActivityService.deleteCustomerActivityByCustomerId(id);
            List<SysContract> sysContractList = sysContractService.GetContractByCustomerId(id);
            for(SysContract sysContract:sysContractList) {
                sysContractLessonService.deleteContractLessonByContractId(sysContract.getId());
                sysUserContractService.deleteUserContractByContractId(sysContract.getId());
                sysContractService.delete(sysContract.getId());
            }
            sysCustomerLessonService.deleteCustomerLessonByCustomerId(id);

            //delete the extension table
            sysCustomerExtensionYlynService.deleteCustomerDetailsByCustomerId(id);

            //now it's time to delete the record
            sysCustomerService.delete(id);
            return MsgUtil.retMsg(SysMessage.DELETE_CUSTOMER_SUCCEED, null, null);
        }catch(Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ErrorUtil.retErrMsg(e);
        }
    }

    @PostMapping(value = "/updateCustomerField")
    @RequiresAuthentication
    public ModelMap updateCustomerField(@RequestHeader("Authorization") String token, @RequestParam Integer id, @RequestParam String fieldName, @RequestParam String fieldValue){
        try{
            String username = JWTUtil.getUsername(token);
            SysCustomer sysCustomer = sysCustomerService.getObjectById(id);
            sysCustomer.initializeUpdateSystemColumns(username);
            switch (fieldName){
                case "status":
                    sysCustomer.setStatus(Integer.parseInt(fieldValue));
                    break;
                case "tag":
                    sysCustomer.setTag(fieldValue);
                    break;
                case "stage_id":
                    sysCustomer.setStage_id(Integer.parseInt(fieldValue));
                    break;
                default:
                    break;
            }
            sysCustomerService.update(sysCustomer);
            return MsgUtil.retMsg(SysMessage.OBSOLETE_CUSTOMER_SUCCEED, "customer", sysCustomer);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @PostMapping(value = "/obsoleteCustomer")
    @RequiresAuthentication
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public ModelMap obsoleteCustomer(@RequestHeader("Authorization") String token, @RequestParam Integer id, @RequestParam String obsolete_tag){
        try{
            String username = JWTUtil.getUsername(token);
            SysCustomer sysCustomer = sysCustomerService.getObjectById(id);
            sysCustomer.initializeUpdateSystemColumns(username);
            sysCustomer.setStatus(2);
            sysCustomer.setObsolete_tag(obsolete_tag);
            sysCustomerService.update(sysCustomer);
            return MsgUtil.retMsg(SysMessage.OBSOLETE_CUSTOMER_SUCCEED, null, null);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping("/pages/getObsoleteCustomers")
    @RequiresAuthentication
    public ModelMap getObsoleteCustomers(@RequestHeader("Authorization") String token,
                                         @RequestParam String orderBy,
                                         @RequestParam String sequence,
                                         @RequestParam Integer offset,
                                         @RequestParam Integer limit) {

        try {
            String order = getOrder(orderBy);
            String seq = getSeq(sequence);

            PageInfo pageInfo = sysCustomerService.getObsoleteCustomers(offset, limit, order, seq);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    private String getSeq(String str){
        if(str.equalsIgnoreCase("asc")){
            return "asc";
        }else if(str.equalsIgnoreCase("desc")){
            return "desc";
        }else{
            return "desc";
        }
    }

    private String getOrder(String str){

        if(str.equalsIgnoreCase("name")){
            return "CAST(name AS CHAR CHARACTER SET gbk)";
        }else if(str.equalsIgnoreCase("employee")){
            return "CAST(employee AS CHAR CHARACTER SET gbk)";
        }else if(str.equalsIgnoreCase("update_time")){
            return "update_time";
        }else if(str.equalsIgnoreCase("channel_tag")){
            return "channel_tag"; //to support sql92 for jsqlparser
        }else if(str.equalsIgnoreCase("obsolete_tag")){
            return "obsolete_tag";
        }else{
            return "update_time";
        }
    }


}
